/**
 * Collections 数据派生 Hook
 * 基于 TanStack Query 提供集合数据及派生计算
 */
import { useMemo } from 'react';
import { useCollectionsBySpace } from '@/hooks/api';
import type { SpaceCollection, TabItem } from '@/types';
import type { CollectionWithTabsDto, TabDto } from '@/api/types';
import type { CollectionsStats } from './types';

/**
 * 将 ISO 时间字符串转换为 Unix 时间戳
 */
const toTimestamp = (value: string): number => {
    const parsed = Date.parse(value);
    return Number.isNaN(parsed) ? Date.now() : parsed;
};

/**
 * 将 TabDto 转换为 TabItem
 */
const mapTabDto = (dto: TabDto): TabItem => ({
    id: dto.id,
    collectionId: dto.collection_id,
    url: dto.url,
    title: dto.title,
    domain: dto.domain,
    favicon: dto.favicon,
    isPinned: dto.is_pin,
    position: dto.position,
    createdAt: toTimestamp(dto.created_at),
    updatedAt: toTimestamp(dto.updated_at),
});

/**
 * 将 CollectionWithTabsDto 转换为 SpaceCollection
 */
const mapCollectionDto = (dto: CollectionWithTabsDto): SpaceCollection => ({
    spaceId: dto.binding.space_id,
    collectionId: dto.collection.id,
    position: dto.binding.position,
    collection: {
        id: dto.collection.id,
        name: dto.collection.name,
        createdAt: toTimestamp(dto.collection.created_at),
        updatedAt: toTimestamp(dto.collection.updated_at),
    },
    tabs: dto.items
        .slice()
        .sort((a, b) => a.position - b.position)
        .map(mapTabDto),
});

/**
 * 获取空间下的集合数据及派生计算
 * @param spaceId - 空间 ID
 * @returns 集合列表、加载状态、错误信息及相关操作函数
 */
export function useCollectionsData(spaceId: number | null) {
    // 使用 TanStack Query 获取数据
    const query = useCollectionsBySpace(spaceId);

    // 转换为 SpaceCollection 格式并按 position 排序
    const collections = useMemo<SpaceCollection[]>(() => {
        if (!query.data) return [];
        return query.data
            .map(mapCollectionDto)
            .sort((a, b) => a.position - b.position);
    }, [query.data]);

    // 构建集合 ID 到集合对象的索引映射（用于快速查找）
    const collectionsMap = useMemo<Record<number, SpaceCollection>>(() => {
        const map: Record<number, SpaceCollection> = {};
        for (const collection of collections) {
            map[collection.collectionId] = collection;
        }
        return map;
    }, [collections]);

    // 计算统计信息
    const stats = useMemo<CollectionsStats>(() => {
        const collectionsCount = collections.length;
        const totalTabsCount = collections.reduce(
            (total, collection) => total + collection.tabs.length,
            0
        );
        return { collectionsCount, totalTabsCount };
    }, [collections]);

    /**
     * 根据集合 ID 获取集合对象
     */
    const getCollectionById = useMemo(
        () => (collectionId: number) => collectionsMap[collectionId],
        [collectionsMap]
    );

    return {
        // 数据
        collections,
        collectionsMap,
        stats,

        // 状态
        isLoading: query.isLoading,
        isError: query.isError,
        error: query.error,
        isFetching: query.isFetching,

        // 操作函数
        getCollectionById,

        // 原始 query 对象（用于高级操作）
        query,
    };
}
